package com.fh.shop.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;


@Component
public class MailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to,String title,String content){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //设置内容
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置发件人
            mimeMessageHelper.setFrom(from);
            //设置收件人
            mimeMessageHelper.setTo(to);
            //设置标题
            mimeMessageHelper.setSubject(title);
            //设置内容
            mimeMessageHelper.setText(content,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    //发送邮件 + 附件
    public void sendMailAppendix(String to, String title, String content, List<String> filePathList){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //设置内容
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //设置发件人
            mimeMessageHelper.setFrom(from);
            //设置收件人
            mimeMessageHelper.setTo(to);
            //设置标题
            mimeMessageHelper.setSubject(title);
            //设置内容
            mimeMessageHelper.setText(content,true);
            //设置附件
            for (String filePath : filePathList) {
                mimeMessageHelper.addAttachment(FileUtil.getFileName(filePath),new File(filePath));
            }
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
